package com.my.blog.website;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.util.Properties;

/**
 * <p>Title         :<br/></p>
 * <p>懒汉式   :<br/></p>
 * <p>
 * Created by run on 2018/1/15.
 */
public class PropertiesUtils4 {
    private static final Logger logger = LoggerFactory.getLogger(PropertiesUtils4.class);
    private static final String CONFIG_NAME = "application.properties";
    private static String path = null;

    private static Long modified = 0L;

    private static Properties props = null;
    private PropertiesUtils4(){
        modified = new File(PropertiesUtils4.class.getClassLoader().getResource(CONFIG_NAME).getPath()).lastModified();
        loadProps();
    }

    public static PropertiesUtils4 getInstance(){
        return PropertiesUtils3Holder.instance;
    }

    private void loadProps(){
        props = new Properties();
        InputStream inputStream = null;
        try {
            path = PropertiesUtils4.class.getClassLoader().getResource(CONFIG_NAME).getPath();
            inputStream = new FileInputStream(path);
            props.load(inputStream);
        }catch (Exception e){
            logger.error("加载application.properties文件发生异常",e);
        }finally {
            try {
                if (null != inputStream){
                    inputStream.close();
                }
            }catch (Exception e){
                inputStream = null;
            }
        }
    }

    private static class PropertiesUtils3Holder {
        public static PropertiesUtils4 instance = new PropertiesUtils4();
    }

    private static boolean isFileModified(){
        boolean returnFlag = Boolean.FALSE;
        File file = new File(PropertiesUtils4.class.getClassLoader().getResource(CONFIG_NAME).getPath());
        if(file.lastModified() > modified){
            logger.info("修改配置文件:{}",CONFIG_NAME);

            modified = file.lastModified();
            returnFlag = Boolean.TRUE;
        }
        return returnFlag;
    }

    public String getProperty(String key){
        return getProperty(key,null);
    }

    public String getProperty(String key,String defaultValue){
        if(StringUtils.isNotBlank(key)){
            if (isFileModified()){
                logger.info("修改了文件，重新加载配置文件");
                loadProps();//重新加载
            }
            return props.getProperty(key);
        }
        return defaultValue;
    }
}
